<?php

namespace Qwadmin\Controller;

class NovelController extends ComController {

    /**
     *  小说列表
     */
    public function index() {
        //$result = M("bookinfo" ,"go_" , "DB_novel")->field('book_title')->limit(10)->select();
        //var_dump($result);
        
        $page = I("p", 1, 'intval');
        $uid = session("uid");
        $keyword = htmlspecialchars(I("keyword", ''), ENT_NOQUOTES);
        $type = htmlspecialchars(I("type", ''), ENT_NOQUOTES); //按新书上架和最新更新
        
        $pram = [
            'page'      =>  $page,
            'keyword'   =>  $keyword,
            'type'      =>  $type
        ];
        $data = D('Novel')->get_recom($pram);
        $pagebar = new \Think\Page($data['count'], 10);
        
        $domain = D("Domain")->getDomain(2);     //获取推广域名
        foreach ($data['list'] as $key => $value) {
            $url = "http://{$domain}/content/{$uid}/{$value['id']}/cps";
            if (!S("{$url}")) {
                S("{$url}", $this->shortUrl($url));
            }
            $data['arts'][$key]['shorturl'] = S("{$url}");
        }
        
        $this->assign("data", $data);
        $this->assign("page", $pagebar->show());
        $this->assign("domain", $domain);
        $this->assign("refid", $uid);
        $this->display();
    }

    public function view(){
        $bookid = I("bookid" , 0 , 'intval');
        $bookinfo = D("Novel")->get_bookinfo($bookid , "id,book_title,book_img,description,booksize");
        $chapter = D("Novel")->get_chapter($bookid);
        $this->assign("data" , [
            'book'      => $bookinfo,
            'chapter'   => $chapter
        ]);
        $this->display();
    }
    
    /**
     *  小说内容
     */
    public function content() {
        header('Content-type:text/json');
        $id = I("id" , 0 , 'intval');
        $json_data = https_request("http://wx.vssnn.com/api/book/get_content/id/{$id}");
        $json_arr = json_decode($json_data ,true);
        //var_dump($json_arr);
        if($json_arr['sort'] > 10){
            echo json_encode(['status' => 0 , 'chapter_name' =>'错误' , 'content' => '推广小说章节只支持10章以内']);die;
        }
        echo json_encode(['status'=>1 , 'content'=> $json_arr['content'] , 'chapter_name' => $json_arr['chapter_name'] ]);die;
    }
    
    public function setbookindex(){
        $bookid = I("bookid" , 0 , 'intval');
        $index = I("index" , 0 , 'intval');
        
        $rows = M("bookinfo")->where(['id' => $bookid])->save(['book_index' => $index]);
        $rows ? $this->ajaxReturn(['status' => 1 , 'msg' => '更新成功']) : $this->ajaxReturn(['status' => 0 , 'msg' => '更新失败']);
    }

    private function shortUrl($longUrl) {
        $longUrl = urlencode($longUrl);
        $api = "http://apiurl.sc2yun.com/url.php?action=jumpurl&url={$longUrl}";
        return https_request($api);
    }

    
    
}
